/*!
 **************************************************************
 *                                                            *  
 *   .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.       *  
 *    |                     ______                     |      *  
 *    |                  .-"      "-.                  |      *  
 *    |                 /            \                 |      *  
 *    |     _          |              |          _     |      *  
 *    |    ( \         |,  .-.  .-.  ,|         / )    |      *  
 *    |     > "=._     | )(__/  \__)( |     _.=" <     |      *  
 *    |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *  
 *    |           "=._"(_     ^^     _)"_.="           |      *  
 *    |               "=\__|IIIIII|__/="               |      *  
 *    |              _.="| \IIIIII/ |"=._              |      *  
 *    |    _     _.="_.="\          /"=._"=._     _    |      *  
 *    |   ( \_.="_.="     `--------`     "=._"=._/ )   |      *  
 *    |    > _.="                            "=._ <    |      *  
 *    |   (_/                                    \_)   |      *  
 *    |                                                |      *  
 *    '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *  
 *                                                            *  
 *           LASCIATE OGNI SPERANZA, VOI CH'ENTRATE           *  
 **************************************************************   
 ******************************************************************
 *  项目名称 : proxy
 *  文件描述 :
 *  文件名称 : requestContext.js
 *  版  本  : v1.0.0.0
 *  说  明  :  
 *  作  者  : night
 *  邮  箱  : 88962800@qq.com
 *  创建时间 : 2019:01-07 14:26 
 ******************************************************************
 Copyright © 2017-2019, All rights reserved.
 ******************************************************************
 */
import EventEmitter from "events";
import Buffer from './buffer';
import uuid from "uuid/v4";
export default class RequestContext extends EventEmitter {
    constructor(socket) {
        super();
        this.key =uuid();
        this.socket = socket;
        this.socket.on('data', buffer => {
            this.buffer && this.buffer.push(buffer);
        });
        this.socket.on('end', () =>{ this.emit('close');this.isEnd =true;});
    }

    buffer = new Buffer();

    bind(socket) {
        if(this.isEnd){return};
        for (let bf of this.buffer.buffer) {
            socket.write(bf);
        }
        this.buffer = null;
        socket.pipe(this.socket);
        this.socket.pipe(socket);
        this.socket.on('close', () => {
            this.socket = null;
            if (socket) socket.destroy();
        })
    }

    close() {
        if (this.socket) this.socket.destroy();
    }
}
